/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: mbuf_yuv_sender.h head file
 */
#ifndef DECODED_MBUF_YUV_SENDER_H
#define DECODED_MBUF_YUV_SENDER_H

#include "image_sender_base.h"
#include "mdc/cam/camera/cameradecodedmbufserviceinterface_skeleton.h"
#include "util.h"
#include "core/types.h"
#include "driver/ascend_hal.h"
#include "securec.h"

using MbufSkeleton = mdc::cam::camera::skeleton::CameraDecodedMbufServiceInterfaceSkeleton;

class DecodedMbufYuvSender : public ImageSenderBase<MbufSkeleton> {
public:
    DecodedMbufYuvSender() = default;
    DecodedMbufYuvSender(uint32_t id, cv::Size s, std::string dir) : ImageSenderBase<MbufSkeleton>(id, s, dir)
    {
        sourceYuvPath = dir;
        if (dir.back() != '/') {
            sourceYuvPath += std::string("/") + "yuvSource.yuv";
        } else {
            sourceYuvPath += "yuvSource.yuv";
        }
#ifdef SAVE_SENDER_FILE
        fp_yuv = fopen(sourceYuvPath.c_str(), "wb+");
#endif
        sec = std::chrono::high_resolution_clock::now();
    }
    ~DecodedMbufYuvSender()
    {
        if (dataSkeleton != nullptr) {
            dataSkeleton->StopOfferService();
            dataSkeleton = nullptr;
        }
        if (handle != nullptr) {
            halBuffDeletePool(handle);
        }
    };

    bool RegisterSender()
    {
        std::cout << "Begin register MBUF image sender." << std::endl;
        auto result = ImageSenderBase<MbufSkeleton>::RegisterSender();
        std::cout << "Finished to register MBUF image sender." << std::endl;
        return result;
    }

    int32_t BufCreatePool(const uint32_t blkSize, const uint32_t blkNum)
    {
        constexpr uint32_t alignSize = 32U;
        mpAttr attr;
        attr.devid = 0;
        attr.mGroupId = 0;
        attr.blkSize = ((blkSize + alignSize) - 1U) & (~(alignSize - 1));
        attr.blkNum = blkNum;
        attr.align = alignSize;
        attr.hugePageFlag = 1U;
        const int32_t ret = halBuffCreatePool(&attr, &handle);
        if (ret != DRV_ERROR_NONE) {
            std::cout << "halBuffCreatePool error: " << ret << std::endl;
            return -1;
        }
        return 0;
    }

    int32_t CopyToMbuf(uintptr_t &mbuf, const uint8_t *src, const uint32_t len) const
    {
        Mbuf *pMbuf = nullptr;
        int32_t ret = halMbufAllocByPool(handle, &pMbuf);
        if (ret != DRV_ERROR_NONE) {
            return -1;
        }
        if (pMbuf == nullptr) {
            return -1;
        }
        void *dst = nullptr;
        uint64_t bufSize = 0U;
        ret = halMbufGetDataPtr(pMbuf, &dst, &bufSize);
        if (ret != 0 || dst == nullptr) {
            halBuffFree(pMbuf);
            return -1;
        }
        if (len > bufSize) {
            halBuffFree(pMbuf);
            return -1;
        }
        if (memcpy_s(reinterpret_cast<uint8_t *>(dst), static_cast<uint64_t>(bufSize), src,
            static_cast<uint64_t>(len)) != 0) {
            halBuffFree(pMbuf);
            return -1;
        }
        ret = halMbufSetDataLen(pMbuf, len);
        if (ret != DRV_ERROR_NONE) {
            halBuffFree(pMbuf);
            return -1;
        }
        mbuf = reinterpret_cast<uintptr_t>(pMbuf);
        return 0;
    }

    void FillImageAndSend(std::string yuvPath, uint32_t seq, int32_t *gStopFlag) override
    {
        (void)gStopFlag;
        std::string path = dir;
        bool isLoop = g_comPara.loop;
        std::vector<std::string> files;
        int32_t fileCnt = getFilesBySort(path, files, g_comPara.fileType);
        if (fileCnt == 0) {
            return;
        }

        do {
            for (auto &file : files) {
                FILE *yuv_file = fopen(file.c_str(), "rb");
                if (g_switchFlag == CN40)
                    yuv_file = nullptr;
                if (yuv_file == nullptr) {
                    std::cout << "Open yuv file failed!" << std::endl;
                    return;
                }

                int32_t frameSize = imgSize.width * imgSize.height * 3 / 2;
                if (fseek(yuv_file, 0, SEEK_END) != 0) {
                    std::cout << "fseek yuv file failed!" << std::endl;
                    return;
                }

                int32_t fileSize = ftell(yuv_file);
                const int32_t size = -1L;
                if (g_switchFlag == CN41)
                    fileSize = size;
                if (fileSize == size) {
                    std::cout << "ftell yuv file failed!" << std::endl;
                    return;
                }

                rewind(yuv_file);
                int32_t frameCount = fileSize / frameSize;
                for (int32_t i = 0; i < frameCount; i++) {
                    DealYUVSend(yuvPath, seq, file, yuv_file);
                }
            }
        } while (isLoop);
#ifdef SAVE_SENDER_FILE
        if (fclose(fp_yuv) != 0) {
            std::cout << " fclose(fp_yuv) != 0 " << std::endl;
        }
#endif
    }

private:
    void HandleFrequency()
    {
        if (g_comPara.frequency != "") {
            int32_t freq = atoi(g_comPara.frequency.c_str());
            if (freq != 0) {
                int32_t sleepTime = CN1000000 / freq;
                usleep(sleepTime);
            }
        } else {
            usleep(CN1000000 / 30); // 30hz
        }
    }

    void DealYUVSend(std::string yuvPath, uint32_t seq, std::string file, FILE *yuv_file)
    {
        int32_t frameSize = imgSize.width * imgSize.height * 3 / 2;
        char *yuvBuff = (char *)malloc(frameSize * sizeof(char));
        if (yuvBuff == NULL) {
            std::cout << "malloc failed!" << std::endl;
            return;
        }
        errno_t ret = memset_s(yuvBuff, frameSize, 0, frameSize);
        if (ret != EOK) {
            std::cout << "memset_s failed: " << ret << std::endl;
            return;
        }
        if (fread(yuvBuff, sizeof(char), frameSize, yuv_file) != frameSize) {
            std::cout << "fread yuvBuff error!" << std::endl;
        }
        cv::Mat YUV420NV12;
        // yuv w:h  1.5
        YUV420NV12.create(imgSize.height * 1.5, imgSize.width, CV_8UC1);
        memcpy_s(YUV420NV12.data, frameSize, yuvBuff, frameSize);
        auto imagePub = dataSkeleton->cameraDecodedMbufEvent.Allocate();
        imagePub->CameraHeader.Seq = seq;
        imagePub->FrameType = static_cast<decltype(imagePub->FrameType)>(Adsfi::HAF_IMAGE_YUV420SP_NV12_UINT8);
        imagePub->Width = imgSize.width;
        imagePub->Height = imgSize.height;
        imagePub->DataSize = frameSize;
        imagePub->CameraHeader.FrameId = file;
        uintptr_t imgdata {};
        (void)CopyToMbuf(imgdata, YUV420NV12.data, frameSize);
        if (imgdata == reinterpret_cast<uintptr_t>(nullptr)) {
            return;
        }
        imagePub->RawData = reinterpret_cast<rawBuffer *>(imgdata);
#ifdef SAVE_SENDER_FILE
        if (fwrite(YUV420NV12.data, 1, frameSize, fp_yuv) != frameSize) {
            std::cout << "fwrite() != frameSize" << std::endl;
        }
#endif
        if (g_comPara.time.empty()) {
            timeval now;
            gettimeofday(&now, NULL);
            imagePub->CameraHeader.Stamp.Sec = now.tv_sec;
            imagePub->CameraHeader.Stamp.Nsec = now.tv_usec * 1000U;
        } else {
            imagePub->CameraHeader.Stamp.Sec = HandleTimeStamp();
        }
        dataSkeleton->cameraDecodedMbufEvent.Send(move(imagePub));
        seq++;
        HandleFrequency();
        free(yuvBuff);
    }

    uint32_t HandleTimeStamp()
    {
        time_t timeStamp = convertTimeStr2TimeStamp(g_comPara.time);
        auto t1 = std::chrono::high_resolution_clock::now();
        int64_t duration = (t1 - sec).count() / 1000000000.0;
        uint32_t time = timeStamp + duration;
        return time;
    }

private:
    poolHandle handle;
    float lastTime = 0.0F;
    std::chrono::high_resolution_clock::time_point sec; // -t used
    std::string sourceYuvPath;
    FILE *fp_yuv;
};

#endif // DECODED_MBUF_YUV_SENDER_H
